package com.example.printservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.printservice.Service.TokenService;
import com.example.printservice.constants.Constants;
import com.example.printservice.entity.TonkeEntity;
import com.example.printservice.result.R;
import com.example.printservice.result.ResultEnum;
import com.example.printservice.utils.ToImg;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@Slf4j
@Api(tags = "")
public class FileController {
    @Value("${constants.filePath}")
    private String uploadFilePath;

    @Autowired
    private ToImg toImg;
    @Autowired
    private TokenService tokenService;

    String token = null;
    String tokenfront = null;

    @RequestMapping("/upload")
    @ApiOperation(value = "上传文件")
    public R httpUpload(MultipartFile file) {
        TonkeEntity byId = tokenService.getById(1);

        if (byId == null) //说明是刚今来打印
        {
            token = UUID.randomUUID().toString();
            tokenfront = token.substring(0, 10);
            String substring = token.substring(10, token.length());
            tokenService.save(new TonkeEntity(1, substring, 1, token));
            return getR(file); //调用上传文件
        } else if (byId.getStatus() > 0 && byId.getStatus() < 2) { //如果数据库中还有数据但是又进行了一次上传文件 进行判断
            boolean b = tokenService.updateById(new TonkeEntity(1, byId.getToken(), 1, token));
            return getR(file);  //调用上传文件
        } else {
            return R.error("想重复卡bug");
        }
    }

    private R getR(MultipartFile file) {
        boolean flag = false;
        JSONObject object = new JSONObject();
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);// 文件名
        String suffix = fileName != null ? fileName.substring(fileName.lastIndexOf(".") + 1) : "";
        for (
                String fileType : Constants.FILE_TYPES) {
            if (fileType.equals(suffix)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            try {
                throw new Exception("不支持的文件格式");
            } catch (Exception e) {
                log.error("不支持的文件格式");
                return R.error();
            }
        }

        File dest = new File(uploadFilePath + '\\' + fileName.substring(0, fileName.lastIndexOf(".")) + UUID.randomUUID() + "." + suffix);
        // 创建文件夹
        if (!dest.getParentFile().

                exists()) {
            Path path = Paths.get(Constants.RESULT_PATH);
            try {
                Path pathCreate = Files.createDirectories(path);
                log.info(pathCreate.toString() + "已创建！");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        String resultPath = null;
        PDDocument document = null;
        try {
            file.transferTo(dest);
            log.info(dest.getPath());
            resultPath = toImg.toImg(dest.getPath());
            int count = new File(resultPath).listFiles().length;
            //            document = PDDocument.load(new File(resultPath));
            object.put("success", ResultEnum.SUCCESS);
            object.put("fileName", fileName);
            object.put("privateName", resultPath);
            object.put("pages", count);
        } catch (
                Exception e) {
            log.error("{}", e);
            object.put("result", ResultEnum.UNKNOWN_ERROR);
        }

//        try {
//            document.close();
//        } catch (IOException e) {
//            throw new RuntimeException("文件关闭异常\n in FileController");
//        }
        return R.ok().put("data", object.toString());
    }
}
